// pages/dispose/index.js
import { listAuditSource, pageMonitorhcRecord } from "../../service/api/api-monitor";

Page({
  data: {
    articleList: [],
    startTime: '',
    endTime: '',
    searchKeyword: '',
    loading: false,
    loadingMore: false,
    onlyProblems: false,
    accountIndex: 0,
    currentPage: 1,
    pageSize: 10,
    total: 0,
    totalPage: 0,
    hasMore: true,
    filterActive: false,

    // 账号筛选数据
    optionsCascadersSourceData: [],

    // 筛选参数
    filterParams: {
      releaseTimes: null,
      isViolation: 1,
      datahubSourceIds: []
    },

    // 搜索参数
    searchParams: {
      dataName: ''
    },

    // 平台ID数组（只在选择全部账号时使用）
    datahubChannelIds: [
      '8117112411979845',
      '8117112410996805',
      '8117112412962885',
      '8117112414076995',
      '8117112419123365',
      '8117112412962886',
      '8117112414994505',
    ]
  },
  getDisposeStateClass(state) {
    if (state === 1) {
      return 'processing';
    } else if (state === 2) {
      return 'warning';
    } else {
      return 'success';
    }
  },

  onLoad() {
    this.loadAuditSourceData();
    this.loadArticleData(true);
  },

  // 加载账号筛选数据
  async loadAuditSourceData() {
    try {
      const res = await listAuditSource({
        datahubChannelIds: [
          '8117112411979845',
          '8117112410996805',
          '8117112412962885',
          '8117112414076995',
          '8117112419123365',
          '8117112412962886',
          '8117112414994505',
        ],
      });

      if (res.code === 0) {
        const options = res.data.map(item => ({
          label: item.name,
          value: item.datahubSourceId,
          datahubChannelId: item.datahubChannelId
        }));

        options.unshift({ label: '全部账号', value: '' });

        this.setData({
          optionsCascadersSourceData: options
        });
      }
    } catch (error) {
      console.error('加载账号数据失败:', error);
    }
  },
  // 文章项点击事件
  onItemClick(e) {
    const id = e.currentTarget.dataset.id;
    const item = e.currentTarget.dataset.item;
    //判断跳转文章还是视频
    if (item.greenTypes[0] && id) {
      if (item.greenTypes[0] === "text") {
        wx.navigateTo({
          url: `/pages/articleDetail/index?id=${id}&type=1`
        });
      } else {
        wx.navigateTo({
          url: `/pages/videoDetail/index?id=${id}&type=1`
        });
      }
    }

  },
  // 加载文章数据
  async loadArticleData(isRefresh = false) {
    if (isRefresh) {
      this.setData({
        loading: true,
        currentPage: 1
      });
    } else {
      this.setData({ loadingMore: true });
    }

    try {
      const params = {
        ...(this.data.accountIndex === 0 ? { datahubChannelIds: this.data.datahubChannelIds } : {}),
        ...this.data.searchParams,
        ...this.data.filterParams,
        current: this.data.currentPage,
        pageSize: this.data.pageSize
      };

      if (params.datahubSourceIds && !Array.isArray(params.datahubSourceIds)) {
        params.datahubSourceIds = [params.datahubSourceIds];
      }

      console.log('请求参数:', params);

      const res = await pageMonitorhcRecord(params);

      if (res.code === 0) {
        const newList = isRefresh ? res.data.data : [...this.data.articleList, ...res.data.data];
        const total = res.data.total || 0;
        const totalPage = Math.ceil(total / this.data.pageSize);
        const hasMore = this.data.currentPage < totalPage;

        this.setData({
          articleList: newList,
          total: total,
          totalPage: totalPage,
          hasMore: hasMore,
          loading: false,
          loadingMore: false
        });
      } else {
        console.error('加载数据失败:', res.message);
        this.setData({
          loading: false,
          loadingMore: false
        });
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('API请求错误:', error);
      this.setData({
        loading: false,
        loadingMore: false
      });
      wx.showToast({
        title: '请求出错',
        icon: 'none'
      });
    }
  },

  // 搜索输入变化
  onSearchChange(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索清除
  onSearchClear() {
    this.setData({
      searchKeyword: '',
      'searchParams.dataName': ''
    });
    this.refreshData();
  },

  // 搜索提交
  onSearchSubmit() {
    this.setData({
      'searchParams.dataName': this.data.searchKeyword
    });
    this.refreshData();
  },

  // 开始时间变化
  onStartTimeChange(e) {
    const startTime = e.detail.value;

    // 如果已经选择了结束时间，且开始时间晚于或等于结束时间，重置结束时间
    if (this.data.endTime && startTime >= this.data.endTime) {
      this.setData({
        startTime: startTime,
        endTime: '' // 清空结束时间
      });
      wx.showToast({
        title: '开始时间已更新，请重新选择结束时间',
        icon: 'none'
      });
    } else {
      this.setData({ startTime });
    }

    this.checkFilterActive();
  },

  // 结束时间变化
  onEndTimeChange(e) {
    const endTime = e.detail.value;

    if (!this.data.startTime) {
      wx.showToast({
        title: '请先选择开始时间',
        icon: 'none'
      });
      return;
    }

    // 结束时间必须大于开始时间（不能等于）
    if (endTime <= this.data.startTime) {
      wx.showToast({
        title: '结束时间必须晚于开始时间',
        icon: 'none'
      });
      return;
    }

    this.setData({ endTime });
    this.checkFilterActive();
  },

  // 计算结束时间的最小可选日期（开始时间后一天）
  getMinEndDate() {
    if (!this.data.startTime) return '2020-01-01';

    const startDate = new Date(this.data.startTime);
    const minEndDate = new Date(startDate);
    minEndDate.setDate(startDate.getDate() + 1);

    return minEndDate.toISOString().split('T')[0];
  },

  // 账号筛选变化
  onAccountChange(e) {
    const index = e.detail.value;
    const selectedAccount = this.data.optionsCascadersSourceData[index];

    this.setData({
      accountIndex: index,
      'filterParams.datahubSourceIds': selectedAccount.value ? [selectedAccount.value] : []
    });

    this.checkFilterActive();
  },

  // 只看问题开关变化
  onSwitchChange(e) {
    this.setData({
      onlyProblems: e.detail.value,
      'filterParams.isViolation': e.detail.value ? 1 : null
    });
    this.checkFilterActive();
  },

  // 应用筛选按钮点击
  onFilterSubmit() {
    // 验证时间选择
    if (this.data.startTime && !this.data.endTime) {
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none'
      });
      return;
    }

    if (!this.data.startTime && this.data.endTime) {
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none'
      });
      return;
    }

    // 更新筛选参数
    const filterParams = {
      releaseTimes: this.data.startTime && this.data.endTime
        ? [this.data.startTime, this.data.endTime]
        : null,
      isViolation: this.data.filterParams.isViolation,
      datahubSourceIds: this.data.filterParams.datahubSourceIds
    };

    this.setData({
      filterParams: filterParams
    }, () => {
      this.refreshData();
    });
  },

  // 检查是否有筛选条件
  checkFilterActive() {
    const active = this.data.onlyProblems ||
      this.data.accountIndex > 0 ||
      this.data.startTime ||
      this.data.endTime;

    this.setData({ filterActive: active });
  },

  // 清除所有筛选
  clearFilters() {
    this.setData({
      startTime: '',
      endTime: '',
      onlyProblems: false,
      accountIndex: 0,
      filterParams: {
        releaseTimes: null,
        isViolation: null,
        datahubSourceIds: []
      }
    }, () => {
      this.refreshData();
      this.setData({ filterActive: false });
    });
  },

  // 刷新数据
  refreshData() {
    this.setData({
      currentPage: 1
    });
    this.loadArticleData(true);
    this.checkFilterActive();
  },

  // 加载更多
  loadMore() {
    if (this.data.loadingMore || !this.data.hasMore) return;

    this.setData({
      currentPage: this.data.currentPage + 1
    }, () => {
      this.loadArticleData(false);
    });
  },

  // 格式化时间显示
  formatTime(timeStr) {
    if (!timeStr) return '';
    return timeStr.replace('T', ' ').substring(0, 16);
  },

  // 获取状态类名
  getStatusClass(state) {
    if (state === undefined || state === 0) {
      return 'status-normal';
    } else if (state === 1) {
      return 'status-warning';
    } else {
      return 'status-problem';
    }
  },

  // 获取状态文本
  getStatusText(state) {
    if (state === undefined || state === 0) {
      return '正常';
    } else if (state === 1) {
      return '警告';
    } else {
      return '问题';
    }
  },

  // 获取平台类名
  getPlatformClass(platform) {
    const platformMap = {
      '微信公众号': 'wechat',
      '微信视频号': 'wechat-channels',
      '微博': 'weibo',
      '抖音': 'douyin',
      '今日头条': 'toutiao',
      '快手': 'kuaishou',
      '哔哩哔哩': 'bilibili',
      '客户端': 'app',
      '网站': 'web'
    };
    return platformMap[platform] || 'default';
  }
});